from flask import render_template, g, jsonify, abort, request
from info import db
from info.common import user_login_data
from info.models import News, Comment, CommentLike, User
from info.modules.news import news_blu
from info.utils.response_code import RET


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    """
    1.根据news_id查询到对应的数据
    :param news_id:
    :return:
    """

    """
    点击排行的显示
    判断用户是否收藏
    """

    user_click = list()
    # 从数据库中查询点击排行靠前的新闻的前6条
    try:
        click_object =  News.query.order_by(News.clicks.desc()).limit(6)
    except Exception as f:
        print(f)
    if not click_object:
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    for clicks in click_object:
        user_click.append(clicks.to_dict())

    # 显示新闻详情页(根据news_id来查询)
    try:
        news_id_object = News.query.get(news_id)
    except Exception as f:
        print(f)
        abort(404)
    if not news_id_object:
        abort(404)
    news = news_id_object.to_dict()
    news_id_object.clicks += 1
    try:
        db.session.commit()
    except Exception as f:
        db.session.rollback()
        print(f)
    # 判断是否用户收藏
    is_collected = False
    # 判断当前用户是否关注过当前作者
    is_followed = False
    # 查询到当前用户的所有粉丝，判断页面的作者是否在里面
    if g.user:
        if news_id_object in g.user.collection_news:
            is_collected = True
        if news_id_object.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed =True

    # 获取当前新闻的评论信息
    try:
        comment_list = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    # 当前用户的所有评论
    comment_id_list = [comment.id for comment in comment_list]
    # 取到当前用户在当前评论中的所有点赞
    comment_user = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                            CommentLike.comment_id.in_(comment_id_list)).all()
    comments = list()
    # 查询出当前用户的所有点赞评论
    comment_clik_id = [comments_id.comment_id for comments_id in comment_user]
    if comment_list:
        for comment in comment_list:
            comment_dict = comment.to_dict()
            comment_dict["is_like"] = False
            comments.append(comment_dict)
            if g.user.id and comment.id in comment_clik_id:
                comment_dict["id_lick"] = True
    data = {
        "user": g.user.to_dict() if g.user else None,
        "user_click":user_click,
        "news":news,
        "is_collected":is_collected,
        "comments":comments,
        "is_followed":is_followed
    }
    return render_template("news/detail.html", data=data)


@news_blu.route("/news_collect", methods=["post"])
@user_login_data
def news_collect():
    """
    用户收藏和取消收藏
    1.接受参数(新闻id（news_id）,是否收藏action )
    2.校验参数
    3.判断是否收藏
    4.返回响应
    :return:
    """
    user = g.user
    # 1.接受参数(新闻id（news_id）,是否收藏action )
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 2.校验参数&用户是否登录
    try:
        news_id = int(news_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户未登录')

    if not news_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in ("collect", "cancel_collect"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news = News.query.get(news_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻数据不存在")

    # 3.判断用户是否收藏(从数据库中查询)
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
    try:
        db.session.commit()
    except Exception as f:
        print(f)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/news_comment", methods=["post"])
@user_login_data
def news_comment():
    """
    评论
    1.接受参数(哪条新闻,评论内容)
    2.校验参数
    3.业务逻辑(将新闻内容添加到数据库)
    4.返回响应(评论的id模型返回)
    :return:
    """
    # 1.接受参数(哪条新闻,评论内容)
    news_id = request.json.get("news_id")
    comments = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    # 2.校验参数
    if not g.user:
        return jsonify(errno=RET.USERERR, errmsg='用户未登录')
    if not all(["news_id", "comment"]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
    try:
        news_id = int(news_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 3.业务逻辑(将新闻内容添加到数据库)
    try:
        news = News.query.get(news_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')
    # 初始化模型(1对多的数据库-->有中间表)
    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = comments
    if parent_id:
        try:
            parent_id = int(parent_id)
        except Exception as f:
            print(f)
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as f:
        print(f)
        db.session.rollback()
        return jsonify(errno = RET.DBERR, errmsg="数据库保存失败")
    return jsonify(errno=RET.OK, errmsg="操作成功", data=comment.to_dict())


@news_blu.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    """
    点赞
    1.获取参数(哪条评论, 哪个新闻，点赞和取消点赞)
    2.校验参数
    3.业务逻辑(点在+1)
    4.返回响应
    :return:
    """
    # 1.获取参数(哪条评论)
    news_id = request.json.get("news_id")
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")
    user = g.user
    # 2.校验参数
    if not all(["action", "news_id", "comment_id"]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        news_id = int(news_id)
        comment_id = int(comment_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 这条评论的查询对象
    try:
        comment = Comment.query.get(comment_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")
    # 点赞+1(一条评论可以被多个人点赞，一个人可以点赞多条评论--->多对多的模型)
    if action not in ("add","remove"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        comment_like = CommentLike.query.filter(CommentLike.comment_id == comment_id,
                                                CommentLike.user_id == user.id).first()
    except Exception as f:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if action == "add":
        # 查看是否添加
        if not comment_like:
            # 初始化模型(增加点赞条数)
            comments = CommentLike()
            comments.user_id = user.id
            comments.comment_id = comment_id
            db.session.add(comments)
            comment.like_count += 1

    else:
        if comment_like:
            db.session.delete(comment_like)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as f:
        print(f)
        db.session.rollback()
        return jsonify(errno=RET.SERVERERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route("/followed_user", methods=['post'])
@user_login_data
def followed_user():
    """
    关注与取消关注
    :return:
    """
    # 被关注的id
    user_id = request.json.get("user_id")
    action = request.json.get("action")
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    if not all(['user_id', 'action']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')
    try:
        user_id = int(user_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.REQERR, errmsg='参数错误')
    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        target_user = User.query.get(user_id)
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")
    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")
    if action == 'follow':
        # 判断被关注用户是否有这个粉丝
        if g.user  in target_user.followers:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        else:
            target_user.followers.append(g.user)
    else:
        # 取消关注，判断当前用户是否在被关在粉丝里
        if g.user not in target_user.followers:
            return jsonify(errno=RET.DATAERR, errmsg='当前未关注')
        else:
            target_user.followers.remove(g.user)
    try:
        db.session.commit()
    except Exception as f:
        print(f)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")
    return jsonify(errno=RET.OK, errmsg='OK')

